import { useServers } from "@/stores/servers";
import { ref } from "vue";
import { sendMessage } from "./message";
import { getConnection, type connectSetting } from "./connect/connection";

export const roomList = ref([] as string[]);
export async function getRoomList() {
    const servers = useServers();
    try {
        const res = await fetch(servers.roomServer + "/room/list", { method: 'GET' });
        const data = await res.json();
        roomList.value = data;
    } catch (reason) {
        roomList.value = [];
        console.log(reason);
    }
}

export async function roomCreate(room: connectSetting) {
    if (roomCheck(room)) return Promise.reject();

    const servers = useServers();
    let url = servers.roomServer + "/room/build/" + room.room + "/" + room.password;
    if (room.enterPassword != undefined) url += "/" + room.enterPassword;

    try {
        const res = await fetch(url, { method: 'GET' });
        const data = await res.text();
        sendMessage(data);
        servers.roomConnection = getConnection(servers.connectSetting);
        await servers.roomConnection?.open();
        await getRoomList();
        return Promise.resolve();
    } catch {
        sendMessage("无法连接到服务器","error");
        return Promise.reject();
    }
}

export async function roomClose(room: connectSetting) {
    if (roomCheck(room)) return Promise.reject();

    const servers = useServers();
    try {
        const res = await fetch(servers.roomServer + "/room/close/" + room.room + "/" + room.password, { method: 'GET' });
        const data = await res.text();
        sendMessage(data);
        await getRoomList();
        return Promise.resolve();
    } catch {
        sendMessage("无法连接到服务器","error");
        return Promise.reject();
    }
}

function roomCheck(room: connectSetting) {
    if (room.room == ''||room.room == undefined) {
        sendMessage("房间名不能为空","warn");
        return true;
    }
    if (room.password == ''||room.room == undefined) {
        sendMessage("房间权限码不能为空","warn");
        return true;
    }

    if (room.userName == '' || room.userName == undefined) {
        sendMessage( '用户名不能为空',"warn")
        return true;
    }
    return false;
}